package com.supermate.supercut.app.service;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import com.supermate.init.util.DateUtil;
import com.supermate.supercut.app.constant.AppConstant;
import com.supermate.supercut.domain.model.ClipboardText;
import com.supermate.supercut.domain.model.FileResource;
import com.supermate.supercut.domain.repo.ClipboardResourceRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Date;

import static com.supermate.supercut.app.utils.SequenceHelper.generateFileNameByTime;

/**
 * @author jiao.zhou
 */
@Service
public class ClipBoardWriteService {

    @Autowired
    ClipboardResourceRepo clipboardResourceRepo;

    public Boolean saveText(String clipBoardName, String clipBoardText) {
        ClipboardText clipboardText = new ClipboardText();
        clipboardText.setClipboardName(clipBoardName);
        clipboardText.setClipboardText(clipBoardText);
        return clipboardResourceRepo.saveOrUpdateClipboardText(clipboardText);
    }

    public void saveFile(String clipboardName, MultipartFile file) throws IOException {
        Path fileDir = AppConstant.getFileAbsolutePath(clipboardName);
        //创建剪切板对应的文件夹
        if (!Files.exists(fileDir)) {
            Files.createDirectories(fileDir);
        }
        //文件在文件系统中的名字 YYYYMMDD
        //todo yyg 确定下originnalFilename是否需要前端配合
        String fileNameInOs = generateFileNameByTime(file.getOriginalFilename());
        Path filePath = fileDir.resolve(fileNameInOs);
        file.transferTo(filePath);
        //save to datebase
        FileResource fileResource = new FileResource();
        fileResource.setClipboardName(clipboardName);
        fileResource.setFileName(file.getOriginalFilename());
        fileResource.setRelativePath(clipboardName + "/" + fileNameInOs);
        clipboardResourceRepo.saveFileResource(fileResource);

    }

}
